package org.systm.security;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.global.AjaxResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.systm.adminuser.entity.AdminUser;
import org.systm.adminuser.entity.UserRole;
import org.systm.adminuser.params.ExhibitAdminUser;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Calendar;
import java.util.stream.Collectors;

public class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    ObjectMapper objectMapper;

    private final static Calendar instance = Calendar.getInstance();

    static {
        instance.add(Calendar.SECOND, 3600);
    }

    public DefaultAuthenticationSuccessHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        FilterChain chain,
                                        Authentication authentication) throws IOException, ServletException {
        AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");

        AdminUser adminUser = (AdminUser) authentication.getPrincipal();
        ExhibitAdminUser exhibitAdminUser = new ExhibitAdminUser();
        exhibitAdminUser.setUsername(adminUser.getUsername());
        exhibitAdminUser.getRoles().addAll(adminUser.getRoles().stream().map(UserRole::getRole).collect(Collectors.toList()));
        exhibitAdminUser.setPhoto(adminUser.getPhoto());

        String token = JWT
                .create()
                .withClaim("id", adminUser.getId())
                .withClaim("perm", "ppp")
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(adminUser.getSalt()));

        exhibitAdminUser.setToken(token);
        AjaxResult entity = AjaxResult.ok(exhibitAdminUser);
        String str = objectMapper.writeValueAsString(entity);
        response.getWriter().write(str);
    }
}
